package com.lksoft.bz;

import java.io.ObjectStreamException;
import java.io.Serializable;


/**
 * A Bead
 * 
 * @author Lake
 *
 */
public class Bead implements Serializable {
	private static final long serialVersionUID = -6169126360932923809L;

	/** RGB color */
	int color;
	
	/** Color name */
	String name;
	
	/**
	 * Field contructor
	 * 
	 * @param color
	 * @param letter
	 * @param name
	 */
	public Bead(int color, String name){
		this.color = color;
		this.name = name;
	}

	/**
	 * Parse from string
	 * @param line
	 */
	public Bead(String line) {
		String[] split = line.split("\t");
		name = split[0];
		
		int r = Long.decode("#"+split[1].substring(0, 2)).intValue();
		int g = Long.decode("#"+split[1].substring(2, 4)).intValue();
		int b = Long.decode("#"+split[1].substring(4, 6)).intValue();
		color = 0xFF << 24 | r << 16 | g << 8 | b; 
	}
	
	@Override
	public String toString(){
		String hex = String.format("%02x%02x%02x", (color>>16)&0xFF, (color>>8)&0xFF, color&0xFF);
		return name + "\t" + hex.toUpperCase();
	}

	public int getColor() {
		return color;
	}


	public String getName() {
		return name;
	}

	public String getRGBString() {
		return String.format("%02x%02x%02x", (color>>16)&0xFF, (color>>8)&0xFF, color&0xFF).toUpperCase();
	}
	
	private Object writeReplace() throws ObjectStreamException{
		return new BeadProxy(this);
	}
}

/**
 * Proxy class for smart serialization ( every bead must be static!! )
 * 
 * @author lake
 *
 */
class BeadProxy implements Serializable {
	private static final long serialVersionUID = 3174804027780437562L;
	
	public int color;

	public BeadProxy(Bead bead) {
		this.color = bead.getColor();
	}

	private Object readResolve() throws ObjectStreamException {
		return BeadDB.get().getBead(color);
	}
}